In JavaScript, some Array
methods do not mutate the existing array that the method was called on, but instead return a new array.
Other methods mutate the array, and their return value differs depending on the method.
reverse
and sort
are mutating methods and, in addition, return the altered version. This rule raises an issue when the
return values of these methods are assigned, which could lead maintainers to overlook the fact that the original array has been modified.
const reversed = a.reverse(); // Noncompliant: mutating method, no need to assign return value
const sorted = b.sort(); // Noncompliant: mutating method, no need to assign return value
Remove the assignment, so that the intent of mutating the original array is clear.
a.reverse();
b.sort();
Or use non-mutating alternatives toReversed
and toSorted
.
const reversed = a.toReversed();
const sorted = b.toSorted();
Alternatively, change a mutating method into a non-mutating alternative using the spread syntax (…
).
const reversed = [...a].reverse();
const sorted = [...b].sort();
Or slice()
to create a copy first.
const reversed = a.slice().reverse();
const sorted = b.slice().sort();